<?php

namespace yunj\core;

/**
 * 内部配置
 * Class Config
 * @package yunj\core
 */
final class Config {

    /**
     * Notes: 配置获取
     * Author: Uncle-L
     * Date: 2021/11/8
     * Time: 18:28
     * @param string $key [配置参数名，第一级为配置文件名。支持多级配置 . 号分割且必须。如：sys.title]
     * 获取admin.php的所有配置
     *  admin.或者admin
     * 获取admin.php里面的entrance
     *  admin.entrance
     * @param null $default [默认值]
     * @param string[] $dir [配置目录]
     * @return mixed
     */
    public static function get(string $key, $default = null, string ...$dir) {
        return self::_get($key, $default, $dir);
    }

    /**
     * @param string $key 配置参数
     * @param null $default 默认值
     * @param array $dirArr 配置目录
     * @return mixed
     */
    private static function _get(string $key, $default = null, array $dirArr) {
        if (!$dirArr) $dirArr = [YUNJ_VENDOR_SRC_PATH . ds_replace("core/config/")];
        $mark = md5(implode(",", $dirArr));
        $keyArr = explode(".", $key);
        // file config
        $fileName = array_shift($keyArr);
        static $config = [];
        if (!isset($config[$mark][$fileName])) {
            $path = [];
            foreach ($dirArr as $v) $path[] = "{$v}{$fileName}.php";
            $config[$mark][$fileName] = self::getFileConfig($path);
        }
        if (!$keyArr || (count($keyArr) === 1 && $keyArr[0] === '')) return $config[$mark][$fileName];
        // filterConfig
        $filterConfig = $config[$mark][$fileName];
        foreach ($keyArr as $k) {
            if (isset($filterConfig[$k])) {
                $filterConfig = $filterConfig[$k];
            } else {
                return $default;
            }
        }
        return $filterConfig;
    }

    /**
     * Notes: 获取配置文件所有配置
     * Author: Uncle-L
     * Date: 2021/11/8
     * Time: 21:06
     * @param string[] $path [配置文件地址]
     * @return array
     */
    private static function getFileConfig(array $path): array {
        $config = [];
        foreach ($path as $v)
            if (file_exists($v)) $config += include $v;
        return $config;
    }

}